package ru.ya.kolemik.servcmd;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import ru.ya.kolemik.servcmd.View.type;
import ru.ya.kolemik.servcmd.servs.ServContext;

public abstract class AbstractServ implements Serv, InitializingBean {
    
    private final Map<type, Method> viewMethods = new HashMap<type, Method>();
    
    protected Logger log = Logger.getLogger(getClass());
    
    public void afterPropertiesSet() throws Exception {
        log.info("Init Bean " + getClass().getName());
        Method[] methods = getClass().getMethods();
        for (Method method : methods) {
            View view = method.getAnnotation(View.class);
            if (view != null) {
                viewMethods.put(view.value(), method);
            }
        }
    }
    
    /**
     * Вытаскивает остаток команды, начиная со слэша номер i
     * 
     * @param command
     *            - команда вида "item/123/delete"
     * @param i
     *            - номер слэша [1..n], например 2
     * @return - в приведённом примере вернёт строку "delete"
     */
    protected static String getSubCommand(String command, int i) {
        if (command == null) {
            return null;
        }
        int position = 0;
        while (i-- > 0) {
            position = command.indexOf("/", position) + 1;
            if (position == 0) {
                return null;
            }
        }
        return command.substring(position);
    }
    
    protected static String getSubCommand(String command) {
        return getSubCommand(command, 1);
    }
    
    public Method getViewMethod(type viewType) {
        return viewMethods.get(viewType);
    }
    
    public final ServContext getContext(HttpServletRequest request) {
        ServContext context = null;
        context = (ServContext) request
                .getAttribute(ServContext.REQUEST_ATTRIBUTE_NAME);
        return context;
    }
}
